import React from 'react';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import {createRoot} from "react-dom/client";
import {Typography} from "@mui/material";

const ConfirmDialog = ({messages = [], choose}) => {
    return (
        <Dialog open={true} onClose={() => choose(false)}>
            <DialogTitle>确认</DialogTitle>
            <DialogContent dividers>
                {messages.length === 1 ?
                    <DialogContentText>{messages[0]}</DialogContentText> :
                    messages.map((msg, index) => <Typography gutterBottom key={index}>{msg}</Typography>)
                }
            </DialogContent>
            <DialogActions>
                <Button onClick={() => choose(false)} color="primary" autoFocus>取消</Button>
                <Button onClick={() => choose(true)} color="primary">确认</Button>
            </DialogActions>
        </Dialog>
    );
};
// message may be a string or an array of strings
export const confirm = (message) => {
    return new Promise((resolve) => {
        const container = document.createElement('div');
        document.body.appendChild(container);
        const root = createRoot(container);

        const handleClose = (choice) => {
            root.unmount();
            document.body.removeChild(container);
            resolve(choice);
        };

        root.render(
            <ConfirmDialog
                messages={Array.isArray(message) ? message : message.split('\n')}
                choose={handleClose}/>
        );
    });
};

